package com.zy.socket.chat_0;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;

/**
 * @Author Gong
 * @Description
 * @dATE 2021/12/19 18:56
 **/
public class Server {
    private HashSet<Socket> allSocket;
    private ServerSocket server;


    public Server() {
        try {
            server = new ServerSocket(8080);
        }catch(IOException e) {

            e.printStackTrace();
        }
        allSocket=new HashSet<Socket>();
    }
    public void startServer() throws IOException{
        while(true) {
            Socket socket =server.accept();
            System.out.println("用户已经进入聊天室");
            allSocket.add(socket);
            ServerThread t= new ServerThread(socket);
            t.start();

        }
    }
    private class ServerThread extends Thread{
        Socket socket;
        public ServerThread(Socket socket) {
            this.socket=socket;
        }
        @Override
        public void run() {
            BufferedReader br=null;
            try {
                br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while(true) {
                    String str=br.readLine();
                    if(str.contains("%EXIT%")) {
                        String tmp=str.split(":")[1]+"用户退出聊天室";
                        sendMessageToALLClient(tmp);
                        allSocket.remove(socket);
                        socket.close();
                        return;
                    }
                    sendMessageToALLClient(str);
                }
            }catch(IOException e) {
                e.printStackTrace();

            }
        }}
    private void sendMessageToALLClient(String str) throws IOException {
        for(Socket s: allSocket) {
            try{
                BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                bw.write(str);
                bw.newLine();
                bw.flush();
            }catch(IOException e) {
                e.printStackTrace();

            }
        }
    }
    public static void main(String[] args) {
        Server s = new Server();
        try {
            s.startServer();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
